﻿using System;
using System.Web;
using System.Text;
using System.Linq;
using System.Web.Mvc;
using XCaptcha.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Collections.Generic;
using Eacademy.Domain.Models;
using Eacademy.Domain.Services;
using Eacademy.Library.Helpers;
using Eacademy.Domain.Repository;
using Eacademy.Library.Membership;
using Eacademy.Domain.Abstractions;

namespace Eacademy.Controllers
{

    public class AccountController : Controller
    {
        //Country Repository
        private readonly IUserRepository _userRepository;

        CustomMembershipProvider provider = (CustomMembershipProvider)Membership.Provider;
        //
        // Dependency Injection enabled constructors
        //

        public AccountController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        //
        // GET: /Index/
        //

        public ActionResult Index()
        {

            return Redirect("/");
        }

        //
        // GET: /Register/
        //

        [HttpPost]
        public ActionResult ForgotPassword(string email, string secondary)
        {
            //TODO: will optimize later
            User userInfo = _userRepository.GetUserByUsername(email.Trim());
            if (userInfo == null)
            {
                this.FlashError("Username does not exist");
                return Redirect("/");
            }

            userInfo.Save();
            //Domain.Models.Profile profile = _profileRepository.GetProfileByUserId(userInfo.UserId);
            Boolean sendToSecondary = String.IsNullOrEmpty(secondary) ? false : true;
            //async?
            //EmailHelper.SendForgotPasswordEmail(userInfo, profile, HttpContext, sendToSecondary);
            //check if null
            this.FlashDone("Reset password request has been sent to your email");
            if (Request.UrlReferrer != null)
                return Redirect(Request.UrlReferrer.LocalPath);
            return Redirect("/");

            //1. Allow the user to verify the Secret/Question for a maximum of 3 to 5 attempts
            //2. On successful validation, Send an e-mail with random generated password with a validity of 24hrs.
            //3. The e-mail must contain only the password but not both username/password.
            //4. When user logs in with temporary password, then user must be forced to create a new password before going to home page.
        }

        public ActionResult ResetPassword(string key, string user)
        {
            if (String.IsNullOrEmpty(key) || String.IsNullOrEmpty(user))
            {
                return Redirect("/");
            }
            User userObject = _userRepository.GetUserByUsername(user);
            // total hours remaining before expiration
            //if ((userObject.UserPasswordKeyExpiryDate.ToDate() - DateTime.Now).TotalHours > 0)
            //{
            var passwordViewModel = new PasswordViewModel { Username = user, PasswordKey = key };
            return View(passwordViewModel);
            //}
            this.FlashError("The forgot password request has expired");
            return Redirect("/");

        }

        [HttpPost]
        public ActionResult ResetPassword(PasswordViewModel passwordViewModel)
        {
            //export user db
            User user = _userRepository.GetUserByUsername(passwordViewModel.Username);
            // total hours remaining before expiration
            //if ((user.UserPasswordKeyExpiryDate.ToDate() - DateTime.Now).TotalHours > 0)
            //{
            //    if (user.UserPasswordKey == passwordViewModel.PasswordKey)
            //    {
            if (_userRepository.ResetPassword(passwordViewModel.Password, (int)user.UserId, user.PasswordSalt))
            {
                this.FlashDone("Password was successfully changed, please login.");
                return Redirect("/");
            }
            this.FlashDone("Password change unsuccessful");
            return Redirect("/");

            //    }
            //}
            this.FlashError("The forgot password request has expired");
            return Redirect("/");
        }

        public ActionResult Verify(string code)
        {
            /*
            User user = _userRepository.GetUserByConfirmationCode(code);
            if (user != null)
            {
                // total hours remaining before expiration
                if ((user.ConfirmationCodeExpiryDate.ToDate() - DateTime.Now).TotalHours > 0)
                {
                    if (_userRepository.VerifyUserByConfirmationCode(code, user.UserId))
                    {
                        this.FlashInfo("Account verification successful");
                        return Redirect("/events/");
                    }
                    this.FlashError("Account verification code has expired");
                    return Redirect("/events/");
                }
            }
            this.FlashError("Account verification failed");*/
            return Redirect("/events/");
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return Redirect("/");
        }

        [HttpPost]
        public ActionResult Login(string username, string password, string rememberme = null)
        {
            if (String.IsNullOrEmpty(username) && String.IsNullOrEmpty(password))
            {
                return Redirect("/");
            }

            if (!provider.ValidateUser(username, password))
            {
                var errorString = new StringBuilder();
                errorString.AppendLine("Incorrect username or password");
                //errorString.AppendLine("<br>");
                //errorString.AppendLine("  <a href=\"#\" id=\"forgot-password-link\"> ");
                //errorString.AppendLine(@"      <span> ");
                //errorString.AppendLine(@"          Forgot your password? ");
                //errorString.AppendLine(@"      </span> ");
                //errorString.AppendLine(@"  </a> ");
                this.FlashError("Invalid login details");
                TempData["LoginError"] = errorString.ToString();
            }
            else
            {
                var user = provider.User;

                //if (!user.Verified)
                //{
                //    // total hours remaining before expiration
                //    /*   if ((user.ConfirmationCodeExpiryDate.ToDate() - DateTime.Now).TotalHours > 0)
                //       {
                //           TempData["LoginError"] = "Please verify your account";
                //           if (Request.UrlReferrer != null) return Redirect(Request.UrlReferrer.LocalPath);
                //       }
                //       // possible delete the account profile and user
                //       TempData["LoginError"] = "Incorrect username or password";
                //       return Redirect("/");*/
                //    Console.WriteLine("Not verified");
                //}

                Boolean rememberMe = String.IsNullOrEmpty(rememberme) ? false : true;

                //FormsAuthentication.SetAuthCookie(user.Username,false);
                var authTicket = new
                               FormsAuthenticationTicket(1, //version
                               username,                    //user name
                               DateTime.Now,                //creation
                               DateTime.Now.AddMinutes(30), //Expiration
                               rememberMe,                  //Persistent (Remember Me)
                               user.Identification);                   //since Classic logins don't have a "Friendly Name"

                var encTicket = FormsAuthentication.Encrypt(authTicket);
                Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                //var profile = provider.Profile;


                switch (provider.User.UserTypeId)
                {
                    case UserTypes.Student:
                        //this.FlashInfo("Please complete your profile to continue");
                        return Redirect("/student/home/");
                    case UserTypes.Mentor:
                        return Redirect(Url.Action("Index", new {Area = "Mentor", Controller = "Home"}));

                }



                TempData["LoginError"] = String.Empty;
            }

            if (Request.UrlReferrer != null)
            {
                string returnurl = HttpUtility.ParseQueryString(Request.UrlReferrer.Query)["returnurl"];
                if (!String.IsNullOrEmpty(returnurl))
                {
                    return Redirect(returnurl);
                }
            }

            //if (!String.IsNullOrEmpty(Request.UrlReferrer.LocalPath))
            //{
            //    return Redirect(Request.UrlReferrer.LocalPath);
            //}
            //Return profile based on user type

            return Redirect("/");

        }

    }
}
